<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="社团" prop="clubName">
        <el-input
          v-model="queryParams.clubName"
          placeholder="请输入社团"
          clearable
          style="width: 120px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户"
          clearable
          style="width: 120px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="queryParams.role" placeholder="成员角色" clearable style="width: 150px">
          <el-option
            v-for="dict in member_role"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="成员状态" clearable style="width: 150px">
          <el-option
            v-for="dict in member_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button  icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" >
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:members:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          :disabled="single"
          @click="handleApprove"
          v-hasPermi="['system:members:approve']"
        >审核</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:members:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:members:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:members:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    

    <el-table v-loading="loading" :data="membersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="头像" align="center" width="80">
        <template #default="scope">
          <el-avatar 
            :size="40" 
            :src="getAvatarUrl(scope.row.avatar || scope.row.userAvatar)" 
            :alt="scope.row.userName"
          >
            <el-icon><User /></el-icon>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="社团" align="center" prop="clubName" width="100" />
      <el-table-column label="用户" align="center" prop="userName" width="100" />
      <el-table-column label="角色" align="center" prop="role" width="120">
        <template #default="scope">
          <dict-tag :options="member_role" :value="String(scope.row.userRole)" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="scope">
          <dict-tag :options="member_status" :value="String(scope.row.status)" />
        </template>
      </el-table-column>
      <el-table-column label="申请理由" align="center" prop="applyReason" show-overflow-tooltip />
      <el-table-column label="拒绝理由" align="center" prop="rejectReason" show-overflow-tooltip />
      <el-table-column label="加入日期" align="center" prop="joinDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.joinDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            v-if="scope.row.status === 0&&scope.row.role!=1"
            link 
            type="success" 
            icon="Check" 
            @click="handleApprove(scope.row)" 
          >通过</el-button>
          <el-button 
            v-if="scope.row.status === 0&&scope.row.role!=1"
            link 
            type="danger" 
            icon="Close" 
            @click="handleReject(scope.row)" 
          >拒绝</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-if="scope.row.role!=0">修改</el-button>
          <el-button link type="warning" icon="Check" @click="handleApprove(scope.row)" v-if="scope.row.role!=0">审核</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-if="scope.row.role!=0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核对话框 -->
    <el-dialog :title="reviewTitle" v-model="reviewOpen" width="500px" append-to-body>
      <el-form ref="reviewFormRef" :model="reviewForm" :rules="reviewRules" label-width="80px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="rejectReason" v-if="reviewForm.status === 3">
          <el-input v-model="reviewForm.rejectReason" type="textarea" placeholder="请输入拒绝原因" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReview">确 定</el-button>
          <el-button @click="cancelReview">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改社团成员关系对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="membersRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="社团ID" prop="clubId">
          <el-input v-model="form.clubId" placeholder="请输入社团ID" />
        </el-form-item> -->
        <!-- <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item> -->
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="dict in member_role"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-select 
            v-model="form.status" 
            placeholder="请选择状态" 
            style="width: 100%"
            @change="handleStatusChange"
          >
            <el-option
              v-for="dict in member_status"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="申请理由" prop="applyReason">
          <el-input v-model="form.applyReason" type="textarea" placeholder="请输入申请理由" />
        </el-form-item>
        <el-form-item 
          label="拒绝理由" 
          prop="rejectReason" 
          v-if="showRejectReason"
        >
          <el-input v-model="form.rejectReason" type="textarea" placeholder="请输入拒绝理由" />
        </el-form-item>
        <el-form-item label="加入日期" prop="joinDate">
          <el-date-picker
            v-model="form.joinDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择加入日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Members">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { User } from '@element-plus/icons-vue'
import { listMembers, getMembers, delMembers, addMembers, updateMembers, approveMember, rejectMember } from "@/api/system/members";

const { proxy } = getCurrentInstance();
const { member_role, member_status } = proxy.useDict("member_role", "member_status");

const membersList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const showRejectReason = ref(false); // 控制拒绝理由显示

// 审核相关变量
const reviewTitle = ref("");
const reviewOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    clubId: undefined,
    userId: undefined,
    role: undefined,
    status: undefined
  },
  rules: {
    clubId: [
      { required: true, message: "社团ID不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    role: [
      { required: true, message: "角色不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ]
  },
  reviewForm: {
    memberIds: [],
    status: 1,
    rejectReason: ""
  },
  reviewRules: {
    status: [
      { required: true, message: "请选择审核结果", trigger: "change" }
    ],
    rejectReason: [
      { required: true, message: "请输入拒绝原因", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules, reviewForm, reviewRules } = toRefs(data);

/** 查询社团成员关系列表 */
function getList() {
  loading.value = true;
  listMembers(queryParams.value).then(response => {
    membersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    clubId: undefined,
    userId: undefined,
    role: undefined,
    status: undefined,
    applyReason: undefined,
    rejectReason: undefined,
    joinDate: undefined
  };
  showRejectReason.value = false;
  proxy.resetForm("membersRef");
}

/** 处理状态变化 */
function handleStatusChange(value) {
  // 仅当状态为拒绝(2)时显示拒绝理由
  showRejectReason.value = value === 3;
  if (value !== 2) {
    form.value.rejectReason = undefined;
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  // 过滤掉没有id的项，确保不会产生null值
  ids.value = selection.filter(item => item && item.id != null).map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加成员关系";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getMembers(id).then(response => {
    form.value = response.data;
    // 确保状态值是数字类型
    if (form.value.status !== undefined) {
      form.value.status = Number(form.value.status);
      showRejectReason.value = form.value.status === 2;
    }
    open.value = true;
    title.value = "修改成员关系";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["membersRef"].validate(valid => {
    if (valid) {
      // 深拷贝表单数据，避免转换影响原始数据
      const submitData = { ...form.value };
      
      // 如果状态不是拒绝状态，清空拒绝理由
      if (submitData.status !== 2) {
        submitData.rejectReason = undefined;
      }
      
      if (submitData.id != null) {
        updateMembers(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMembers(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 审核相关方法
/** 批量通过按钮操作 */
function handleApprove(row) {
  console.log(row)
  console.log(ids.value)
  const memberIds = ids.value;
  // 过滤掉null和undefined值
  if (memberIds.length === 0) {
    //proxy.$modal.msgError("请选择要审核的成员");
    //return;
    memberIds[0] = row.id
  }
  reviewForm.value.memberIds = memberIds;
  reviewForm.value.status = 2;
  reviewTitle.value = "审核通过";
  reviewOpen.value = true;
}

/** 批量拒绝按钮操作 */
function handleReject(row) {
  const memberIds = row.id || ids.value;
  // 过滤掉null和undefined值
  if (memberIds.length === 0) {
    proxy.$modal.msgError("请选择要审核的成员");
    return;
  }
  reviewForm.value.memberIds = memberIds;
  reviewForm.value.status = 3;
  reviewTitle.value = "审核拒绝";
  reviewOpen.value = true;
}

/** 提交审核 */
function submitReview() {
  proxy.$refs["reviewFormRef"].validate(valid => {
    if (valid) {
      // 确保memberIds不为空且不包含null值
      if (!reviewForm.value.memberIds || reviewForm.value.memberIds.length === 0) {
        proxy.$modal.msgError("请选择要审核的成员");
        return;
      }
      
      const validIds = reviewForm.value.memberIds.filter(id => id != null);
      if (validIds.length === 0) {
        proxy.$modal.msgError("请选择要审核的成员");
        return;
      }
      
      // 更新memberIds为有效值
      reviewForm.value.memberIds = validIds;
      
      // 调试信息：显示请求数据
      console.log("审核请求数据:", {
        memberIds: reviewForm.value.memberIds,
        status: reviewForm.value.status,
        rejectReason: reviewForm.value.rejectReason
      });
      
      if (reviewForm.value.status === 2) {
        approveMember(reviewForm.value).then(response => {
          proxy.$modal.msgSuccess("审核通过成功");
          reviewOpen.value = false;
          getList();
        }).catch(error => {
          console.error("审核通过失败:", error);
          proxy.$modal.msgError("审核通过失败");
        });
      } else {
        rejectMember(reviewForm.value).then(response => {
          proxy.$modal.msgSuccess("审核拒绝成功");
          reviewOpen.value = false;
          getList();
        }).catch(error => {
          console.error("审核拒绝失败:", error);
          proxy.$modal.msgError("审核拒绝失败");
        });
      }
    }
  });
}

// 取消审核
function cancelReview() {
  reviewOpen.value = false;
  resetReviewForm();
}

// 重置审核表单
function resetReviewForm() {
  reviewForm.value = {
    memberIds: [],
    status: 1,
    rejectReason: ""
  };
  proxy.resetForm("reviewFormRef");
}

/** 删除按钮操作 */
function handleDelete(row) {
  const memberIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除成员关系ID为"' + memberIds + '"的数据项？').then(function() {
    return delMembers(memberIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/member/export", {
    ...queryParams.value
  }, `members_${new Date().getTime()}.xlsx`);
}

function getAvatarUrl(avatar) {
  // 如果没有头像，返回空字符串
  if (!avatar || avatar === "" || avatar === null) {
    return '';
  }
  
  // 如果头像URL已经是完整的URL（以http或https开头），直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar;
  }
  
  // 使用与user.js相同的逻辑：直接拼接baseURL和头像路径
  return import.meta.env.VITE_APP_BASE_API + avatar;
}

getList();
</script>

<style scoped>
/* 头像样式 */
.el-avatar {
  border: 2px solid #e4e7ed;
  transition: all 0.3s ease;
}

.el-avatar:hover {
  border-color: #409eff;
  transform: scale(1.05);
}

/* 表格行悬停效果 */
.el-table tbody tr:hover .el-avatar {
  border-color: #409eff;
}

/* 确保头像在表格中居中显示 */
.el-table .el-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style>